package com.cdhospital.admincontroller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONException;
import org.json.JSONObject;
public class ss {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
    	System.setProperty ("jsse.enableSNIExtension", "false");
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static String httpPostWithJSON(String url,String w) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        
       JSONObject params = new JSONObject();
        params.put("BaseRequest", new JSONObject().put("Uin", 1005088001).put("Sid", w).put("Skey", "").put("DeviceID", "e149681966821199"));
        StringEntity entity = new StringEntity(params.toString(),"utf-8");//解决中文乱码问题    
        entity.setContentEncoding("UTF-8");    
        entity.setContentType("application/json");    
        httpPost.setEntity(entity);
        System.out.println();
        
    
//        表单方式
//        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 
//        pairList.add(new BasicNameValuePair("name", "admin"));
//        pairList.add(new BasicNameValuePair("pass", "123456"));
//        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   
        
        
        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he,"UTF-8");
        }
        return respContent;
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    
    public static net.sf.json.JSONObject  doPost(String url,JSONObject json){
    	
          BufferedReader in = null;
      DefaultHttpClient client = new DefaultHttpClient();
      String result=null;
      HttpPost post = new HttpPost(url);
      net.sf.json.JSONObject response = null;
      try {
        StringEntity s = new StringEntity(json.toString());
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
          result = EntityUtils.toString(res.getEntity());// 返回json格式：
          response = net.sf.json.JSONObject.fromObject(result);
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      return response;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    } 
    public static void main(String[] args) throws Exception {
        //发送 GET 请求
        String s=sendGet("https://login.weixin.qq.com/jslogin", "fun=new&lang=zh_CN&appid=wx782c26e4c19acffb");
        s=s.substring(s.indexOf("\"")+1, s.lastIndexOf("\""));
      System.out.println(s);
       System.out.println("https://login.weixin.qq.com/qrcode/"+s);
      String erweima=sendGet("https://login.weixin.qq.com/qrcode/"+s, "");
       //获取二维码少秒状态   get
      //https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=gd94hc3_fg==&tip=0&r=-1160587432&_=1452859503803
      String satuts=null;
      boolean flag=true;
      String date=new Date().getTime()+"";
      while(flag){
    	 	 satuts=ss.sendGet("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login", "loginicon=true&uuid="+s+"&tip=0&r=-"+date+""+"&_=1452859503803"); 
    	     String  satut=satuts.substring(satuts.indexOf("=")+1, satuts.indexOf(";"));
    	     if(satut.equals("200")){
    	    	 System.err.println("登录成功");
    	    	 flag=false;
    	    	break;
    	     }
    	     else if(satut.equals("201")){
    	    	 System.err.println("正在扫描");
    	     }
    	     else if(satut.equals("408")){
    	    	 System.err.println("已经超时");
    	    	  s=ss.sendGet("https://login.weixin.qq.com/jslogin", "fun=new&lang=zh_CN&appid=wx782c26e4c19acffb");
    	    	    s=s.substring(s.indexOf("\"")+1, s.lastIndexOf("\""));
    	    	  System.out.println(s);
    	    	   System.out.println("https://login.weixin.qq.com/qrcode/"+s);
    	     	
    	     }
    	  }
    
     satuts=satuts.substring(satuts.indexOf("\"")+1, satuts.lastIndexOf("\""));
     System.err.println(satuts);
      String ticket=satuts.substring(satuts.indexOf("ticket")+7, satuts.indexOf("uuid")-1);
      System.out.println("ticket:"+ticket);
      String uuid=satuts.substring(satuts.indexOf("uuid")+5, satuts.indexOf("lang")-1);
      System.out.println("uuid:"+uuid);
      System.out.println("scan:"+date);
      
    String message=  sendGet("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage", "ticket="+ticket+"&uuid="+uuid+"&lang=zh_CN&scan="+date+"&fun=new");
    System.out.println(message);
    Document dom=DocumentHelper.parseText(message);
    Element root=dom.getRootElement();
    String skey=root.element("skey").getText();
    String wxsid=root.element("wxsid").getText();
    String pass_ticket=root.element("pass_ticket").getText();
    String wxuin=root.element("wxuin").getText();
  Integer a=Integer.parseInt(wxuin);
   
    System.out.println(skey);
    System.out.println(wxsid);
    System.out.println(pass_ticket);
    System.out.println(wxuin);
    
    JSONObject params = new JSONObject();
    //1746295111
    params.put("BaseRequest", new JSONObject().put("Uin", a).put("Sid", wxsid).put("Skey", "").put("DeviceID", "e149681966821199"));
    //https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=en_US&pass_ticket=KlRMZmPcELxJHikrTsq6UEuDiy%252BZn1wFQ1VoeVAHUls82tXXB4L89ePbSghP6ICI&r=1452862903198&seq=0&skey=@crypt_3bb2969_5d9682fbe6794c9437337ef278f6615c
     System.err.println(params);
    String list=httpPostWithJSON("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit", wxsid);
      System.out.println(list);
       net.sf.json.JSONObject li=     doPost("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact", params);
       System.out.println(li);
       
       //退出
       //https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxlogout?redirect=1&type=1&skey=%40crypt_3f5b6fd7_e26160a3198431a1c3b4ae9f0f5f6757
       sendPost("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxlogout", "redirect=1&type=1&skey="+skey);
//     / System.out.println(erweima);
       /* //发送 POST 请求
        String sr=sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
        System.out.println(sr);*/
    }
}